//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import type { NodeProps } from "reactflow";
import type { NodeInfo } from '@/api/project_dataview';
import ProjectNodeWrap from '../ProjectNodeWrap';
import { Button, Descriptions, Space, Tag } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { observer } from 'mobx-react';
import { useDataViewStores } from '@/pages/DataView/store';
import {  API_COLL_CUSTOM, API_COLL_GRPC, API_COLL_OPENAPI, ENTRY_TYPE_API_COLL, ENTRY_TYPE_DOC, ENTRY_TYPE_DRAW, ENTRY_TYPE_PAGES, ENTRY_TYPE_SPRIT, get as get_entry, type GetResponse as GetEntryResponse } from "@/api/project_entry";
import { get_session } from '@/api/user';
import type * as NoticeType from '@/api/notice_type';
import { listen } from '@tauri-apps/api/event';
import { WebviewWindow } from '@tauri-apps/api/window';
import moment from 'moment';
import { LinkEntryInfo } from '@/stores/linkAux';


const RefEntryNode = (props: NodeProps<NodeInfo>) => {
    const dataViewStore = useDataViewStores();

    const [dataResponse, setDataResponse] = useState<GetEntryResponse | null>(null);

    const loadDataResponse = async () => {
        const sessionId = await get_session();
        const res = await get_entry({
            session_id: sessionId,
            project_id: dataViewStore.projectStore.projectId,
            entry_id: props.data.node_data.RefTargetId ?? "",
        });
        setDataResponse(res);
    };

    useEffect(() => {
        loadDataResponse();
    }, []);

    useEffect(() => {
        const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
            const notice = ev.payload;
            if (notice.EntryNotice?.UpdateEntryNotice != undefined && notice.EntryNotice.UpdateEntryNotice.entry_id == props.data.node_data.RefTargetId) {
                loadDataResponse();
            }
        });
        return () => {
            unListenFn.then((unListen) => unListen());
        };
    }, []);

    return (
        <ProjectNodeWrap title={
            <>
                {dataResponse != null && dataResponse.code == 0 && (
                    <span>
                        {dataResponse.entry.entry_type == ENTRY_TYPE_SPRIT && "工作计划"}
                        {dataResponse.entry.entry_type == ENTRY_TYPE_DOC && "项目文档"}
                        {dataResponse.entry.entry_type == ENTRY_TYPE_DRAW && "绘图白板"}
                        {dataResponse.entry.entry_type == ENTRY_TYPE_PAGES && "静态网页"}
                        {dataResponse.entry.entry_type == ENTRY_TYPE_API_COLL && "接口集合"}
                    </span>
                )}
            </>
        } nodeData={props} canChangeBgColor
            extraButtonList={[
                <Button type="text" icon={<ReloadOutlined />} onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    loadDataResponse();
                }} />
            ]}>
            {dataResponse != null && (
                <>
                    {dataResponse.code != 0 && <span style={{ color: "red" }}>{dataResponse.err_msg}</span>}
                    {dataResponse.code == 0 && (
                        <div>
                            <a style={{ fontSize: "20px", fontWeight: 700 }} onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                const notice: NoticeType.AllNotice = {
                                    ClientNotice: {
                                        OpenLinkInfoNotice: {
                                            link_info:new LinkEntryInfo("",dataViewStore.projectStore.projectId,props.data.node_data.RefTargetId ?? ""),
                                        },
                                    },
                                };
                                const mainWindow = WebviewWindow.getByLabel("main");
                                mainWindow?.emit("notice", notice);
                            }}>{dataResponse.entry.entry_title}</a>
                            {dataResponse.entry.entry_type == ENTRY_TYPE_SPRIT && (
                                <Descriptions column={1}>
                                    <Descriptions.Item label="开始日期">
                                        {moment(dataResponse.entry.extra_info.ExtraSpritInfo?.start_time ?? 0).format("YYYY-MM-DD")}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="结束日期">
                                        {moment(dataResponse.entry.extra_info.ExtraSpritInfo?.end_time ?? 0).format("YYYY-MM-DD")}
                                    </Descriptions.Item>
                                    {(dataResponse.entry.extra_info.ExtraSpritInfo?.non_work_day_list ?? []).length > 0 && (
                                        <Descriptions.Item label="非工作日">
                                            <Space style={{ flexWrap: "wrap" }}>
                                                {(dataResponse.entry.extra_info.ExtraSpritInfo?.non_work_day_list ?? []).map(day => (
                                                    <Tag key={day}>{moment(day).format("YYYY-MM-DD")}</Tag>
                                                ))}
                                            </Space>
                                        </Descriptions.Item>
                                    )}
                                </Descriptions>
                            )}
                            {dataResponse.entry.entry_type == ENTRY_TYPE_API_COLL && (
                                <Descriptions column={1}>
                                    <Descriptions.Item label="接口类型">
                                        {dataResponse.entry.extra_info.ExtraApiCollInfo?.api_coll_type == API_COLL_GRPC && "GRPC接口"}
                                        {dataResponse.entry.extra_info.ExtraApiCollInfo?.api_coll_type == API_COLL_OPENAPI && "OPENAPI接口"}
                                        {dataResponse.entry.extra_info.ExtraApiCollInfo?.api_coll_type == API_COLL_CUSTOM && "自定义接口"}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="访问地址">
                                        {dataResponse.entry.extra_info.ExtraApiCollInfo?.default_addr ?? ""}
                                    </Descriptions.Item>
                                </Descriptions>
                            )}
                        </div>
                    )}
                </>
            )}
        </ProjectNodeWrap>
    )
};

export default observer(RefEntryNode);
